<template>
  <div>
    <cl-crud :ref="setRefs('crud')" :on-refresh="onRefresh" @load="onLoad">
      <el-row type="flex" align="middle">
        <!-- 刷新按钮 -->
        <cl-refresh-btn />
        <!-- 新增按钮 -->
        <cl-add-btn />
        <!-- 删除按钮 -->
        <!-- <cl-multi-delete-btn /> -->
        <cl-export-btn type="success" :columns="table.columns" />
        <cl-filter label="标签系统类型">
          <el-select size="mini" filterable :disabled="isDisabled ? true : false" v-model="form.system_type"
            @change="searchSubmit" style="width: 20px">
            <!-- <el-option :key='null' :value="null" label="全部"></el-option> -->
            <el-option :key='null' :value='null' label="全部"></el-option>
            <el-option :key=0 :value=0 label="程序设计"></el-option>
            <el-option :key=1 :value=1 label="机械原理"></el-option>
            <el-option :key=2 :value=2 label="课程造型"></el-option>
            <el-option :key=3 :value=3 label="内容标签"></el-option>
          </el-select>
        </cl-filter>

        <cl-flex1 />
        <!-- 关键字搜索 -->
        <cl-search-key v-model="searchValue"></cl-search-key>
      </el-row>

      <el-row>
        <!-- 数据表格 -->
        <cl-table :ref="setRefs('table')" v-bind="table" @row-click="onRowClick">
          <!-- 行新增 -->
          <template #slot-add="{ scope }">
            <el-button type="text" size="mini" @click="upsertAppend(scope.row)">新增</el-button>
          </template>
          <!-- 行转移 -->
          <template #slot-move="{ scope }">
            <!-- <el-button type="text" size="mini" @click="toMove(scope.row)">转移</el-button> -->
            <el-button type="text" size="mini" @click="open(scope.row)">转移</el-button>
          </template>

        </cl-table>
      </el-row>

      <el-row type="flex">
        <cl-flex1 />
        <!-- 分页控件 -->
        <cl-pagination />
      </el-row>

      <!-- 新增、编辑 -->
      <cl-upsert :ref="setRefs('upsert')" v-bind="upsert">

      </cl-upsert>

    </cl-crud>
    <!-- <cl-dialog title="标签转移" v-model="visible">
      <p>少年，我看你骨骼精奇，是万中无一的武学奇才，维护世界和平就靠你了</p>
    </cl-dialog> -->
    <cl-form ref="formRef">
      <!-- 内嵌crud -->
      <template #slot-crud="scope">
        <cl-crud @load="onLoad">
          <!-- {{ scope }} -->
          <div class="loee_tree">
            <el-input v-model="filterText" placeholder="请输入要查询的标签,可以模糊查询" />
            <el-tree ref="treeRef" :data="labelList" :props="{ label: 'name' }" default-expand-all
              :filter-node-method="filterNode" highlight-current @node-click="handleNodeClick" />

          </div>
        </cl-crud>
      </template>

    </cl-form>
    <!-- <cl-label-move :ref="setRefs('label-move')" @success="refresh({ page: 1 })" /> -->
  </div>

</template>

<script lang="ts">
import { defineComponent, inject, reactive, onMounted, ref, resolveComponent, h, watch } from "vue";
import { CrudLoad, Upsert, Table, RefreshOp, FormRef, FormItem } from "cl-admin-crud-vue3/types";
import { useRefs } from "/@/core";
import { deepTree } from "/@/core/utils";
import { ElMessage } from "element-plus";


export default defineComponent({
  name: "labelSysCom",
  props: {
    system_type: [Number],
    isDisabled: [Boolean],
    props: Object
  },
  setup(props) {
    const { refs, setRefs } = useRefs();
    // 请求服务
    const service = inject<any>("service");

    // 新增、编辑配置
    const upsert = reactive<Upsert>({
      items: [
        {
          prop: "name",
          label: "标签名称",
          span: 24,
          component: {
            name: "el-input",
            // options: student_list.value,
            props: {
              placeholder: "请输入标签名称",
              filterable: true
            },
            onChange: (value: any) => {
              refs.value.upsert.type += value;
            }
          },
          rules: {
            required: true,
            message: "标签名称不能为空"
          }
        },
        // {
        //   // type:"tabs",
        //   prop: "type",
        //   label: "标签类型",
        //   span: 24,
        //   component: {
        //     name: "el-input",
        //     // options: student_list.value,
        //     props: {
        //       placeholder: "请输入标签类型",
        //       filterable: true,
        //     }
        //   },
        //   rules: {
        //     required: true,
        //     message: "标签类型不能为空"
        //   }
        // },
        {
          prop: "system_type",
          label: "标签类型",
          span: 24,
          component: {
            name: "el-select",
            options: [
              // { "value": null, "label": "全部" },
              { "value": 0, "label": "程序设计" },
              { "value": 1, "label": "机械原理" },
              { "value": 2, "label": "课程造型" },
              { "value": 3, "label": "内容标签" },
            ],
            // options: student_list.value,
            props: {
              placeholder: "请选择标签系统类型",
              filterable: true
            }
          },
          rules: {
            required: true,
            message: "标签系统类型不能为空"
          }
        },
        {
          prop: "parentId",
          label: "上级标签",
          span: 24,
          component: {
            name: "labelTree",
            onChange: async ({ type, system_type }) => {
              refs.value.upsert.form.type = type + "/"
              refs.value.upsert.form.system_type = system_type
            },
          },

        },
      ]
    });

    // 表格配置
    const table = reactive<Table>({
      props: {
        "row-key": "id"
      },
      columns: [
        // {
        // 	type: "selection",
        // 	width: 60
        // },
        // {
        // 	type: "index",
        // 	label: "#",
        // 	width: 60
        // },
        // {
        //   prop: "type",
        //   label: "标签类型",
        //   align: "left",
        //   // width: 120
        // },
        {
          prop: "name",
          label: "标签名称",
          align: "left",
          width: 300
        },

        {
          prop: "system_type",
          label: "标签系统类型",
          dict: [
            {
              label: "程序设计",
              value: 0,
              type: "danger"
            },
            {
              label: "机械原理",
              value: 1,
              type: "info"
            },
            {
              label: "课程造型",
              value: 2
            },
            {
              label: "内容标签",
              value: 3
            }
          ]
          // width: 120
        },
        {
          label: "操作",
          type: "op",
          buttons: ["slot-add", "slot-move", "edit", "delete"]
        }
      ]
    });

    // crud 加载
    function onLoad({ ctx, app }: CrudLoad) {
      // 绑定 service
      ctx.service(service.labelSysService).done();
      app.refresh({ system_type: form.system_type });
    }

    // 刷新监听
    function onRefresh(_: any, { render }: RefreshOp) {
      service.labelSysService.list({ system_type: form.system_type, keyWord: searchValue.value }).then((list: any[]) => {
        // list.map((e) => {
        // 	e.permList = e.perms ? e.perms.split(",") : [];
        // });

        render(deepTree(list), {
          total: list.length
        });
        console.log(list, "===========");

        // deepTree(list)
      });
    }

    // 刷新列表
    function refresh(params: any) {
      refs.value.crud.refresh(params);
    }

    // 行点击展开
    function onRowClick(row: any, column: any) {
      if (column.property && row.children) {
        refs.value.table.toggleRowExpansion(row);
      }
    }

    // 子集新增
    function upsertAppend({ type, id, system_type }: any) {
      refs.value.crud.rowAppend({
        parentId: id,
        type: type + "/",
        system_type: system_type
      });
    }

    const formRef = ref<FormRef>();


    const items: FormItem[] = [
      {
        label: "选择标签:",
        props: {
          prop: "name",
          labelWidth: "75px",
        },
        component: {
          name: "slot-crud",
          props: {
            myProp: 'bar'
          }
        }
      },
    ];
    const labelList = ref([])
    async function getLabelList(system_type) {
      labelList.value = await service.labelSysService.list({ system_type: system_type }).then(deepTree);
      labelList.value.unshift({id:null,name:"一级节点"})
      console.log(labelList.value, '\\\\\\\\');

    }



    function open(row) {
      getLabelList(row.system_type)
      // console.log(formRef.value)
      formRef.value?.open({
        width: "500px",
        title: "标签转移",
        props: {
          labelWidth: "140px"
        },
        items,


        on: {
          open(form, { done, close }) {
            console.log(form, "________");
            console.log(done, "++++++++");

          },
          submit(data, { done, close }) {
            console.log(data, "data");
            console.log(row);
            // if (curNode.value) {
              if (row.id !== curNode.value){
                row.parentId = curNode.value
                updateLabelParent(row)
                curNode.value = null
                done();
                close();
              }else{
                ElMessage({message:"不能选择自己",type:"warning"})
              }
              done();
            // }
            
          },
        }
      });
    }
    let curNode = ref(null)
    const updateLabelParent = (data) => {
      console.log(data, "++++++++");

      service.labelSysService.update(data).then((res) => {
        ElMessage.success("转移成功");
        refs.value.crud.refresh()
      })
    }

    const handleNodeClick = (e?) => {
      curNode.value = e?.id
      console.log(e, "eeeeeeeeeee");

    }
    const filterText = ref('')

    const treeRef = ref("")
    watch(filterText, (val) => {
      treeRef.value!.filter(val)
    })

    const filterNode = (value, data) => {
      console.log(value, "111111");
      console.log(data, "222222");

      if (!value) return true
      return data.name.includes(value)
    }
    // 移动标签
    async function toMove(e?: any) {
      visible.value = true

      // let ids = [];
      // ids = [e.id];
      // // if (!e) {
      // //   ids = selects.ids;
      // // } else {
      // //   ids = [e.id];
      // // }
      // console.log(refs.value["label-move"],"88888888888888888");

      // refs.value["label-move"].toMove(ids);
    }
    // 自定义筛选
    const form = reactive({
      system_type: null,
    });

    if (props.system_type !== undefined) {
      form.system_type = props.system_type
    }



    // 筛选按钮提交
    const searchSubmit = function (e: any) {
      refs.value.crud.refresh({ system_type: form.system_type });
    };

    const searchValue = ref('')

    onMounted(() => {
      // 设置默认值
      // searchSubmit();
    });

    const visible = ref(false)

    return {
      refs,
      setRefs,
      upsert,
      table,
      onLoad,
      onRefresh,
      onRowClick,
      upsertAppend,
      form,
      searchSubmit,
      searchValue,
      toMove,
      refresh,
      visible,
      open,
      formRef,
      labelList,
      handleNodeClick,
      filterNode,
      filterText,
      treeRef
    };
  }
});
</script>
<style>
.el-overlay.is-message-box {
  z-index: 3000 !important;
}

.loee_tree {
  border: 1px solid #eee;
  border-radius: 3px;
  padding: 2px;
}
</style>
